export const exportAndDownloadByBuffer = async (request, fileName = '') => {
  const res = await request;
  if (!res) return;
  const disposition = res.headers.get('Content-Disposition');
  const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
  const matches = filenameRegex.exec(disposition);
  let filename;
  if (matches != null && matches[1]) {
    filename = matches[1].replace(/['"]/g, '');
  }
  if (res) {
    downloadArrayBuffer(
      'application/octet-stream,charset=UTF-8',
      await res.arrayBuffer(),
      fileName || decodeURIComponent(filename),
    );
  }
  return res;
};

export const downloadArrayBuffer = (type, data, fileName) => {
  const blob = new Blob([data], {
    type,
  });
  const elink = document.createElement('a');
  elink.download = fileName;
  elink.style.display = 'none';
  elink.href = URL.createObjectURL(blob);
  document.body.appendChild(elink);
  elink.click();
  URL.revokeObjectURL(elink.href); // 释放URL 对象
  document.body.removeChild(elink);
};

export const downloadByUrl = async (fileName, url) => {
  const iframe = document.createElement('iframe');
  iframe.style.display = 'none'; // 防止影响页面
  iframe.style.height = '0px'; // 防止影响页面
  iframe.src = url;
  document.body.appendChild(iframe); // 这一行必须，iframe挂在到dom树上才会发请求
  // 5分钟之后删除（onload方法对于下载链接不起作用，就先抠脚一下吧）
  setTimeout(() => {
    iframe.remove();
  }, 5 * 60 * 1000);
};

export function isPlainObject(obj) {
  return typeof obj === 'object' && obj !== null && obj.constructor === Object;
}

export function getFileNameFromURL(url) {
  // 使用正则表达式从 URL 中提取文件名
  const matches = url?.match(/\/([^/?#]+)$/);
  if (matches) {
    return decodeURIComponent(matches[1]);
  }
  // 如果无法匹配，返回null或者你认为合适的默认值
  return null;
}

export const getFontScale = () => {
  const testDOM = document.createElement('div');
  testDOM.style.fontSize = '10px';
  document.body.appendChild(testDOM);
  // 获取设置系统字号后真实font-size值
  const realFontSize = Number.parseFloat(
    window.getComputedStyle(testDOM).fontSize,
  );
  document.body.removeChild(testDOM);
  // const scale = 10 / realFontSize;
  return 10 / realFontSize;
};
